package com.niit.onlinemusicserver.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.niit.onlinemusicserver.common.R;
import com.niit.onlinemusicserver.mapper.CartListMapper;
import com.niit.onlinemusicserver.model.domain.CartList;
import com.niit.onlinemusicserver.model.request.CartListRequest;
import com.niit.onlinemusicserver.model.request.CartListRespo;
import com.niit.onlinemusicserver.service.CartListService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 购物车接口实现
 * @author Jason
 * @date 2023.6.29
 */
@Service
public class CartListServiceImpl extends ServiceImpl<CartListMapper, CartList> implements CartListService {

  @Autowired
  private CartListMapper cartListMapper;

  @Override
  public R addCartList(CartListRequest cartListRequest) {
    CartList cartList = new CartList();
    BeanUtils.copyProperties(cartListRequest, cartList);
    cartList.setCreateTime(new Date());
    int insert = 0;
    try {
      insert  = cartListMapper.insert(cartList);
    }catch (DataAccessException e){
      e.printStackTrace();
      if(e.getMessage().contains("idx_cart_list_usersongid_unique")){
        return R.warning("购物车中已存在相同歌曲");
      }
    }catch (Exception e){
      e.printStackTrace();
      return R.error("加入购物车时发生错误："+e.getMessage());
    }

    if ( insert > 0) {
      return R.success("添加成功");
    } else {
      return R.error("添加失败");
    }
  }

  @Override
  public R deleteCartList(Integer userId, List<Integer> songIds) {
    try {
      cartListMapper.delCartListBySongId(userId,songIds);
    }catch (Exception e){
      e.printStackTrace();
      return R.fatal("删除失败");
    }

    return R.success("删除成功");
  }

  @Override
  public R allCartList(Integer userId) {
    if(userId == null){
      return R.error("参数输入错误");
    }
    CartList cartList = new CartList();
    cartList.setUserId(userId);
    List<CartListRespo> cartListRespos = null;
    try {
      cartListRespos = cartListMapper.selectCartLists(cartList);
    }catch (Exception e){
      e.printStackTrace();
      return R.fatal(e.getMessage());
    }
    return R.success(null, cartListRespos);
  }
}

